package com.tools.demo.login.secret;


import com.tools.demo.login.secret.exception.RsaException;

import java.security.*;

/**
 * 随机获取一对公私钥对
 *
 * @author Haviven
 * @since 2022/5/25
 **/
public class RsaKey {

    private final RsaPrivateKey privateKey;

    private final RsaPublicKey publicKey;

    public RsaKey() {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RsaException(e);
        }
        keyPairGenerator.initialize(512);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        this.privateKey = new RsaPrivateKey(privateKey);
        this.publicKey = new RsaPublicKey(publicKey);
    }

    public RsaPrivateKey getPrivateKey() {
        return privateKey;
    }

    public RsaPublicKey getPublicKey() {
        return publicKey;
    }
}
